import { ref, onMounted, onUnmounted } from 'vue';

function useWebRTC() {
    const localVideoRef = ref(null);
    const remoteVideoRef = ref(null);
    let localStream = null;
    let remoteStream = null;
    let peerConnection = null;

    async function startVideoCall() {
        try {
            // 获取本地视频流
            localStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });

            // 在本地视频元素上显示本地流
            if (localVideoRef.value) {
                localVideoRef.value.srcObject = localStream;
            }

            // 创建RTCPeerConnection对象
            peerConnection = new RTCPeerConnection();

            // 将本地流添加到RTCPeerConnection对象
            localStream.getTracks().forEach((track) => {
                peerConnection.addTrack(track, localStream);
            });

            // 监听远程流
            peerConnection.addEventListener('track', (event) => {
                remoteStream = event.streams[0];

                // 在远程视频元素上显示远程流
                if (remoteVideoRef.value) {
                    remoteVideoRef.value.srcObject = remoteStream;
                }
            });

            // 创建并发送SDP Offer
            const offer = await peerConnection.createOffer();
            await peerConnection.setLocalDescription(offer);

            // 发送offer到另一端并等待应答answer
            const answer = await sendOffer(offer);

            // 设置另一端的应答answer
            await peerConnection.setRemoteDescription(answer);
        } catch (e) {
            console.error('视频通话启动失败', e);
        }
    }

    function sendOffer(offer) {
        // TODO: 实现发送offer的逻辑，可以使用WebSocket或其他方式将offer发送到另一端
        // 并等待对方的应答answer，并返回answer作为函数结果
    }

    // 在组件挂载时启动视频通话
    onMounted(() => {
        startVideoCall();
    });

    // 在组件卸载时关闭视频通话
    onUnmounted(() => {
        if (peerConnection) {
            peerConnection.close();
        }
    });

    return {
        localVideoRef,
        remoteVideoRef,
    };
}

export default useWebRTC;